from flask import Flask, redirect, url_for, request, render_template, flash
import json, re, datetime, os, time

import _log

####################################################################################################

app = Flask(__name__)


####################################################################################################

def _getTimeFromRow(log):
    objDatetime = None

    ret = re.search(r'\d{2}-\d{2} \d{2}:\d{2}:\d{2}', log)
    if ret is not None:
        objDatetime = datetime.datetime.strptime('2019-' + ret.group(0), "%Y-%m-%d %H:%M:%S")

    return objDatetime


####################################################################################################

class ObjSingle:
    def __init__(self, keyword=None, objDatetime=None, delta=None, log=None):
        self.keyword = keyword
        self.objDatetime = objDatetime
        self.delta = delta
        self.log = log


def _process_single(keyword, log):
    ret_dict = dict()  # keyword->[objSingle1, objSingle2, ...]

    keywords = keyword.split('\n')
    logs = log.split('\n')

    for log in logs:  # 在每一行中
        for keyword in keywords:  # 找每一个关键字
            if keyword in log:
                objDatetime = _getTimeFromRow(log)
                if objDatetime is None:
                    continue

                listObj = ret_dict.get(keyword, None)
                if listObj is None:
                    ret_dict[keyword] = listObj = []
                    listObj.append(ObjSingle(keyword=keyword, objDatetime=objDatetime, log=log))
                else:
                    listObj.append(
                        ObjSingle(keyword=keyword, objDatetime=objDatetime,
                                  delta=(objDatetime - listObj[-1].objDatetime),
                                  log=log))
    return ret_dict


####################################################################################################

class ObjTogether:
    def __init__(self, objDatetime=None, delta=None, log=None, keyword=None):
        self.objDatetime = objDatetime
        self.delta = delta
        self.log = log
        self.keyword = keyword


def _process_together(keyword, log):
    list_ret = []

    keywords = keyword.split('\n')
    logs = log.split('\n')

    first = True
    for log in logs:  # 在每一行中
        for keyword in keywords:  # 找每一个关键字
            if keyword in log:
                objDatetime = _getTimeFromRow(log)
                if first:
                    list_ret.append(ObjTogether(objDatetime=objDatetime, log=log, keyword=keyword))
                    first = False
                else:
                    list_ret.append(
                        ObjTogether(objDatetime=objDatetime, delta=(objDatetime - list_ret[-1].objDatetime), log=log,
                                    keyword=keyword))
                    break

    return list_ret


####################################################################################################

@app.route('/')
def index():
    return render_template('index.html')


def _response(ret_count, ret_str):
    ret_json = {
        'ret_count': ret_count,
        'ret_str': ret_str
    }

    return json.dumps(ret_json)


@app.route('/doProcess', methods=['POST', 'GET'])
def doProcess():
    if request.method == 'POST':
        try:
            keyword = request.form['keyword']
            type = request.form['type']
            log = request.form['log']
        except:
            return _response('NA', 'get request.form fail!')

        if type == 'single':
            ret_dict = _process_single(keyword, log)

            ret_count, ret_str = 0, ''
            for key, value in ret_dict.items():
                ret_count += 1
                for objSingle in value:
                    ret_str += '%s\t%s\t%s\t%s\n' % (
                        objSingle.keyword, objSingle.objDatetime, objSingle.delta, objSingle.log)
                ret_str += '\n'

            return _response(ret_count, ret_str)
        else:
            ret_list = _process_together(keyword, log)

            ret_count, ret_str = 0, ''
            for objTogether in ret_list:
                ret_count += 1
                ret_str += '%s\t%s\t%s\t%s\n' % (
                    objTogether.objDatetime, objTogether.delta, objTogether.keyword, objTogether.log)

            return _response(ret_count, ret_str)

    return _response('NA', 'invalid operation!')


if __name__ == '__main__':
    # 模块
    _log.init(app)

    # 网页
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

    app.run(
        host='127.0.0.1',
        port=8000,
        debug=True,
        threaded=True
    )
